define([
    'text!planmanage/addfileplan/templates/AddFilePlan_first.html',
    'planmanage/addfileplan/views/StrategyTree',
    'planmanage/addfileplan/views/AddFilePlan_variable'
], function(AddFilePlanFirstViewTpl, StrategyTreeView, VariableView) {
    var nodeIdTreeObj;// 所属系统下拉树
    var nodeIdTree_OK = false;// 所属系统下拉树数据加载完成
    return fish.View.extend({
        template: fish.compile(AddFilePlanFirstViewTpl),
        i18nData: fish.extend({}),
        views: {
            '.strstegy-tree-view': new StrategyTreeView()
        },
        events: {},

        initialize: function() {
            // 获取计划表单数据
            fish.on('getPlanFormData', $.proxy(this.getPlanFormData, this));
            // 获取计划信息
            fish.on('getPlanInfo', $.proxy(this.getPlanInfo, this));
            // 计划表单数据的回绑
            fish.on('setFilePlanForm', $.proxy(this.setFilePlanForm, this));
        },

        serialize: function() {
            return this.i18nData;
        },

        //这里用来初始化页面上要用到的fish组件
        afterRender: function() {
            var me = this;
            // 操作类型
            $('input[name="operType"]').combobox({
                placeholder : "请选择操作类型",
                dataTextField : "name",
                dataValueField : "value",
                setEditable : false,
                value : "0",
                dataSource : [ {
                    name : "体检&备份&清理",
                    value : "0"
                }, {
                    name : "体检&清理",
                    value : "1"
                }, {
                    name : "体检",
                    value : "2"
                }, {
                    name : "自定义脚本",
                    value : "3"
                }],
                change: change
            });
            function change(){
                var operType = $(this).val();
                me.operTypeShow(operType);
            };
            // 执行方式，选中事件
            $("input[name=execType]").click(function(){
                me.execTypeShow();
            });
            me.execTypeShow();
            // 执行频率，选中事件
            $("input[name=execFrequency]").click(function(){
                me.execFrequencyShow();
            });
            me.execFrequencyShow();
            // 生失效时间
            $('input[name="effDate"],input[name="expDate"]').datetimepicker({
                buttonIcon : 'calendar',
                viewType:'date',
                format : 'yyyy-mm-dd'
            });
            // 循环周期
            $('input[name="cycleDay"]').spinner({
                min : "1"
            })
            // 开始时间
            $('input[name="startTime"]').datetimepicker({
                //viewType : 'datetime',
                format : 'dd'+'日 '+'hh:ii:ss',
                initialDate:new Date(2016, 4, 1),
                startDate:new Date(2016, 4, 1, 0),
                endDate:new Date(2016, 4, 31, 23, 59),
                container:'#startTimeBox'
            });
            // 执行时间
            $('input[name="cycleType"]').click(function() {
                if (this.value == 0) {
                    $('input[name="startTime"]').datetimepicker('destroy').val('').datetimepicker({
                        buttonIcon : 'calendar',
                        viewType : 'datetime',
                        format : 'dd日hh:ii:ss',
                        initialDate:new Date(2016, 4, 1),
                        startDate:new Date(2016, 4, 1, 0),
                        endDate:new Date(2016, 4, 31, 23, 59),
                        container:'#startTimeBox',
                        autoClose: true
                    });
                } else {
                    $('input[name="startTime"]').datetimepicker('destroy').val('').datetimepicker({
                        buttonIcon : 'time',
                        viewType : 'time',
                        format : 'hh:ii:ss'
                    });
                }
            });
            // 排除日期
            $('select[name="specialDay"]').multiselect({
                displaySelectedOptions : false // 选中的不再显示在列表
            });

            // 所属系统，下拉树
            var nodeId_setting = {
                async: {
                    enable: true,
                    contentType: "application/json",
                    url: webRoot + 'common/sysModule/queryAllForTree.do',
                    type: 'post'
                },
                view: {
                    dblClickExpand:false,
                    selectedMulti: false //如果为true,按住ctrl可以多选，false为单选 
                },
                data: {
                    simpleData: {
                        enable: true,
                        idKey: "id",
                        pIdKey: "pId",
                        rootPId: 0
                    }
                },
                callback: {
                    onClick: nodeIdOnClick,
                    onAsyncSuccess: nodeIdOnAsyncSuccess
                }
            };
            
            var nodeIdTree = $.fn.zTree.init($("#nodeId_tree"), nodeId_setting);
            nodeIdTreeObj = $.fn.zTree.getZTreeObj("nodeId_tree");
            function nodeIdOnClick(){
                nodes = nodeIdTree.getSelectedNodes();
                var nodeIdInput = $('input[name="nodeId"]');
                // 设置控件的其他属性：vId，为真正的value
                nodeIdInput.attr("vId",nodes[0].id).val(nodes[0].name);
                hideNodeIdTree();
            };
            function nodeIdOnAsyncSuccess(){
                nodeIdTree_OK = true;
            };
            //下拉树相对位置，随着窗口联动
            function nodeIdTreePos(){
                var inputObj = $('input[name="nodeId"]');
                var inputObjOffSet = $('input[name="nodeId"]').offset();
                    var $treePs = $("#nodeId_commbox_tree").css({left:inputObjOffSet.left + "px", top: inputObj.outerHeight() + "px",width:inputObj.outerWidth() + "px",'z-index':9999});
                    return $treePs;
                    }
            $('input[name="nodeId"]').click(function(){
                nodeIdTreePos().slideDown("fast");
                $(window).resize(function(){
                    nodeIdTreePos();
                });
                $("body").bind("mousedown", onBodyDownNode);
            });
            function onBodyDownNode(event) {
                if (!(event.target.name == "nodeId" || event.target.id == "nodeId_commbox_tree" || $(event.target).parents("#nodeId_commbox_tree").length>0)) {
                    hideNodeIdTree();
                }
            };
            function hideNodeIdTree(){
                $("#nodeId_commbox_tree").fadeOut("fast");
                $("body").unbind("mousedown", onBodyDownNode);
            };
        },

        operTypeShow: function(operType){
            if(operType == "2" || operType == "3"){
                $("#needCheck").hide();
            }else{
                $("#needCheck").show();
            }
            if(operType == "0"){
                $("#sourceFileZipSwitch").show();
                $("#targetFileZipSwitch").show();
            }else{
                $("#sourceFileZipSwitch").hide();
                $("#targetFileZipSwitch").hide();
            }
        },

        execTypeShow: function(){
            switch ($("input[name=execType]:checked").attr("value")) {
            case "1":// 自动执行
                if($("input[name=execFrequency]:checked").attr("value") == "1"){// 执行频率：单次执行
                    $("#execFrequency,#startTime").show();
                }else{
                    $("#execFrequency,#cycleType,#startTime,#specialDay").show();
                }
                break;
            case "2":// 手动执行
                if($("input[name=execFrequency]:checked").attr("value") == "1"){// 执行频率：单次执行
                    $("#execFrequency,#startTime").hide();
                }else{
                    $("#execFrequency,#cycleType,#startTime,#specialDay").hide();
                }
                break;
            default:
                break;
            }
        },

        execFrequencyShow: function(){
            switch ($("input[name=execFrequency]:checked").attr("value")) {
            case "0":// 循环执行
                $("#cycleType,#specialDay").show();
                $('input[name=cycleDay]').attr('data-rule','required; integer; range[1~1000]');
                break;
            case "1":// 单次执行
                $("#cycleType,#specialDay").hide();
                if(act != 'edit' && act != 'draft'){
                    $("input[name=cycleDay]").attr('data-rule','').resetValid();
                    // 选择日期
                    $($('input[name="cycleType"]')[0]).prop('checked',true);
                    $('input[name="startTime"]').datetimepicker('destroy').val('').datetimepicker({
                        buttonIcon : 'calendar',
                        viewType : 'datetime',
                        format : 'dd日hh:ii:ss',
                        initialDate:new Date(2016, 4, 1),
                        startDate:new Date(2016, 4, 1, 0),
                        endDate:new Date(2016, 4, 31, 23, 59),
                        container:'#startTimeBox',
                        autoClose: true
                    });
                }
                break;
            default:
                break;
            }
        },

        // 获取计划表单数据
        getPlanFormData: function(strategyName){
            // 判断策略名称是否重复
            if(VariableView.getStrategyNameIsRepeated()){
                return;
            }
            $('#planForm').validator({
                timely:0,
                ignore:':hidden'//任何不可见的元素，都不作验证
            });
            // 验证输入值的正确
            if($("#planForm").isValid()){
            // if(true){
                // 表单数据
                var planFormData = $("#planForm").form("value");
                planFormData.dmPlanId = dmPlanId;
                planFormData.nodeId = $('input[name="nodeId"]').attr("vId");
                planFormData.strategyName = strategyName;
                // 重组排除日期，用","隔开
                if(planFormData.specialDay != null&&$.type(planFormData.specialDay) === "array"){
                    planFormData.specialDay=planFormData.specialDay.join(',');
                }
                // 判断生失效时间
                if(planFormData.expDate <= planFormData.effDate && planFormData.expDate != "" && planFormData.effDate != ""){
                    fish.toast('warn', "失效时间不能小于生效时间");
                    return false;
                }
                // 判断执行时间是不是在生失效时间之内
                var expDate = planFormData.expDate.replace('-','/').replace('-','/');
                var effDate = planFormData.effDate.replace('-','/').replace('-','/');
                var a = (Date.parse(expDate) - Date.parse(effDate)) / 3600 / 1000 / 24;
                if(planFormData.execType == 1 && planFormData.execFrequency == 0 && planFormData.cycleType == 0 && a < 31){// 按月循环
                    fish.toast('warn', "按月循环的计划，生失效时间必须大于31天");
                    return false;
                }
                var expYear = planFormData.expDate.split(" ")[0].split("-")[0];
                var effYear = planFormData.effDate.split(" ")[0].split("-")[0];
                var expMonth = planFormData.expDate.split(" ")[0].split("-")[1];
                var effMonth = planFormData.effDate.split(" ")[0].split("-")[1];
                var expDay = planFormData.expDate.split(" ")[0].split("-")[2];
                var effDay = planFormData.effDate.split(" ")[0].split("-")[2];
                var startDay = planFormData.startTime.split(" ")[0].substring(8,10);
                if(planFormData.execFrequency == 1 && planFormData.execType == 1 && a < 31){// 单次执行、自动执行、生失效时间间隔不足一个月
                    if(effMonth < expMonth || effYear < expYear){
                        if(startDay < effDay && startDay > expDay){
                            fish.toast('warn', "执行时间要在生失效时间内");
                            return false;
                        }
                    }else if(effMonth == expMonth){
                        if(startDay < effDay || startDay > expDay){
                            fish.toast('warn', "执行时间要在生失效时间内");
                            return false;
                        }
                    }
                }
                if(planFormData.operType == 2){
                    planFormData.needCheck = "F";
                }
                if(planFormData.execType == 2 || planFormData.execFrequency == 1){
                    planFormData.cycleDay = null;
                }

                // 判断计划名称是否重复
                fish.ajax({
                    async : false,
                    url: ctx + '/baseconfig/dmfileplan/planNameIsRepeated.do',
                    showMask: false,  //是否自动显式全局遮罩
                    showError: true, //在出现异常时自动显示异常信息，后台需要返回的数据格式：{code:'ERROR-1001',message:'登录失败'}
                    timeout: 30000,   //超过3秒显式全局遮罩，此参数在showMask为true时才有效
                    data: planFormData,
                    beforeSend: function(){
                        $.blockUI({message : "判断计划名称是否重复：数据提交中,请稍候..."});
                    },
                    complete: function(xhr, status){
                        $.unblockUI();
                        if(status == 'timeout'){
                            fish.toast('error', "网络请求超时");
                            return;
                        }
                        if(xhr.responseJSON.success == false){
                            fish.toast('error',xhr.responseJSON.msg);
                            return;
                        }
                        if(xhr.responseJSON){// 计划名称重复，不能继续下一步
                            fish.toast('warn','计划名称重复，请重新输入');
                            VariableView.setPlanForm_OK(false);
                            return;
                        }else{
                            VariableView.setPlanFormData(planFormData);
                            VariableView.setPlanForm_OK(true);
                        }                        
                    },
                    //【注意】如果你在这里配置了自己的error处理函数，fish.ajax就不会自动帮你显示异常信息了！
                    error:function(){
                        $.unblockUI();
                    }
                });
            }else{
                VariableView.setPlanForm_OK(false);
            }
        },

        // 获取计划信息
        getPlanInfo: function(){
            var me = this;
            fish.ajax({
                url: ctx + '/baseconfig/dmfileplan/getPlanInfo.do',
                showMask: false,  //是否自动显式全局遮罩
                showError: true, //在出现异常时自动显示异常信息，后台需要返回的数据格式：{code:'ERROR-1001',message:'登录失败'}
                timeout: 30000,   //超过3秒显式全局遮罩，此参数在showMask为true时才有效
                data: {dmPlanId: dmPlanId},
                beforeSend: function(){
                    $.blockUI({message : "获取计划信息中,请稍候..."});
                },
                complete: function(xhr, status){
                    $.unblockUI();
                    if(status == 'timeout'){
                        fish.toast('error', "网络请求超时");
                        return;
                    }
                    // 计划表单数据的回绑
                    me.setFilePlanForm(xhr.responseJSON);
                },
                //【注意】如果你在这里配置了自己的error处理函数，fish.ajax就不会自动帮你显示异常信息了！
                error:function(){
                    $.unblockUI();
                }
            });
        },

        // 计划表单数据的回绑
        setFilePlanForm: function(dmPlanPO){
            $.blockUI({message : "数据加载中,请稍候..."});
            var me = this;
            // 判断所属系统的数据是否加载完成
            if(!nodeIdTree_OK){
                setTimeout(function(){
                    me.setFilePlanForm(dmPlanPO);
                }, 1000);
                return;
            }

            //计划名称
            $('input[name="planName"]').val(dmPlanPO.planName);

            //所属系统
            var node = nodeIdTreeObj.getNodeByParam("id", dmPlanPO.nodeId);
            if(node != null){
                $('input[name="nodeId"]').attr("vId",node.id);
                $('input[name="nodeId"]').val(node.name);
            }

            //源数据类型
            var sourceType = dmPlanPO.sourceType;
            $("input[name='sourceType'][value="+sourceType+"]").attr("checked",true);

            // 源文件是否压缩
            $("input[name='sourceFileZipSwitch'][value="+dmPlanPO.sourceFileZipSwitch+"]").attr("checked",true); 

            // 目标文件是否压缩
            $("input[name='targetFileZipSwitch'][value="+dmPlanPO.targetFileZipSwitch+"]").attr("checked",true); 
            
            //循环方式
            $("input[name='cycleType'][value="+dmPlanPO.cycleType+"]").attr("checked",true);

            //循环周期
            $('input[name="cycleDay"]').val(dmPlanPO.cycleDay);

            // 执行时间
            if (dmPlanPO.cycleType == 0) {
                $('input[name="startTime"]').datetimepicker('destroy').val(dmPlanPO.startTime.substring(0,2) + '日' + dmPlanPO.startTime.substring(2,4) + ':' + dmPlanPO.startTime.substring(4,6) + ':00').datetimepicker({
                    buttonIcon : 'calendar',
                    viewType : 'datetime',
                    format : 'dd日hh:ii:ss',
                    initialDate:new Date(2016, 4, dmPlanPO.startTime.substring(0,2), dmPlanPO.startTime.substring(2,4), dmPlanPO.startTime.substring(4,6)),
                    startDate:new Date(2016, 4, 2, 0),
                    endDate:new Date(2016, 4, 31, 23, 59),
                    container:'#startTimeBox',
                    autoClose: true
                });
            }else{
                $('input[name="startTime"]').datetimepicker('destroy').val(dmPlanPO.startTime.substring(2,4) + ':' + dmPlanPO.startTime.substring(4,6) + ':00').datetimepicker({
                    buttonIcon : 'time',
                    viewType : 'time',
                    format : 'hh:ii:ss'
                });
            }

            //排除日期
            if(dmPlanPO.specialDay != null){
                var ids = dmPlanPO.specialDay.split(",");
                $('select[name="specialDay"]').multiselect('value', ids);
            }
            
            //执行频率
            $("input[name='execFrequency'][value="+dmPlanPO.execFrequency+"]").attr("checked",true);
            me.execFrequencyShow();

            //执行类型
            var execType = dmPlanPO.execType;
            $("input[name='execType'][value="+execType+"]").attr("checked",true);
            me.execTypeShow();

            //目标数据类型
            $("input[name='targetType'][value="+dmPlanPO.targetType+"]").attr("checked",true);

            //操作类型
            var operType = dmPlanPO.operType;
            $('input[name="operType"]').combobox('value',operType+"");
            this.operTypeShow(operType);

            //清理方式
            $("input[name='needCheck'][value="+dmPlanPO.needCheck+"]").attr("checked",true);

            //生失效时间
            $('input[name="effDate"]').val(dmPlanPO.effDate.substring(0,dmPlanPO.effDate.indexOf(' ')));
            $('input[name="expDate"]').val(dmPlanPO.expDate.substring(0,dmPlanPO.expDate.indexOf(' ')));

            //描述
            $('textarea[name="planDesc"]').val(dmPlanPO.planDesc);

            // 策略树
            fish.trigger('setStrategyTree', dmPlanPO.dmPlanId);

            nodeIdTree_OK = false;
            $.unblockUI();
        }
    });
});